<?php
class CompaniesController extends AppController {

    public $name = 'Companies';
    public $components = array('Upload');
    public $helpers = array('Text');

    public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('*');
		$this->__setLayout();
	}
    private  function __setLayout(){
        if($this->Bayon->isLogging()){
            $this->layout = 'user';
        }else{
            $this->layout = 'company';
        }
        $this->checkAjax();
    }
    public function admin_index() {
		$this->Company->recursive = 0;
		$this->set('companies', $this->paginate());
	}


	public function admin_add() {
		if (!empty($this->data)) {
			$this->Company->create();
			if ($this->Company->save($this->data)) {
				$this->Session->setFlash(__('The company has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The company could not be saved. Please, try again.', true));
			}
		}
	}

	public function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid company', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Company->save($this->data)) {
				$this->Session->setFlash(__('The group has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The company could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Company->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for company', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Company->delete($id)) {
			$this->Session->setFlash(__('Company deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Company was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
/**
 * Front page Section
 * 
 */
        public function edit(){
            if(!empty($this->data)){
                $this->data['Company']['guid'] = $this->data['Company']['slug'];
                $slug = FULL_BASE_URL.$this->base.'/company/'.$this->data['Company']['slug'];
                $this->data['Company']['slug'] = $slug;

                $this->Company->id = $this->data['Company']['id'];
                if($this->Company->save($this->data)){

                    //init for update classification company
                    if(isset($this->data['Company']['children']))
                        $classifyId = $this->data['Company']['children'];
                    else
                        $classifyId = $this->data['Company'] ['classification'];

                    $this->Company->ClassificationCompany->id = $this->data['Company']['clCompanyId'];
                    $this->Company->ClassificationCompany->saveField('classification_id', $classifyId);

                }

                $this->redirect($slug);
                
            }else{
                $companyId = $this->params['companyid'];
                if(!$companyId){
                    $this->set('error', true);
                }else{
                    $company = $this->Company->find('first', array('conditions' => array('Company.id' => $companyId), 'recursive' => -1));
                    //pr($company); die();
                    if($this->checkPermission($company['Company']['user_id'])){
                        //select country
                        $countries = $this->Company->Country->find('list', array('recursive' => -1));
                        $this->set('countries', $countries);
                        $this->set('userId', $this->Bayon->userId());

                        //select classification
                        $this->loadModel('Classification');
                        $this->set('classifications', $this->Classification->getClassifications());

                        //current classification
                        $clasCompany = $this->Company->ClassificationCompany->getByCompany($company['Company']['id']);
                        //set ClassificationCompany Id
                        $this->set('clCompanyId', $clasCompany['ClassificationCompany']['id']);

                        $currentClas = $this->Classification->getClassify($clasCompany['ClassificationCompany']['classification_id']);
                        if($currentClas['Classification']['parent_id'] != 0){
                            $this->set('parentId', $currentClas['Classification']['parent_id']);
                            $clasChild =$this->Classification->getClassifications( $currentClas['Classification']['parent_id'] );
                            $this->set('clasChild', $clasChild);
                            $this->set('childId', $currentClas['Classification']['id']);
                            //pr($clasChild); die();
                        }else{
                            $this->set('parentId', $currentClas['Classification']['id']);
                        }

                        $this->set('company', $company);
                        $this->set('error', false);

                        $this->set('userId', $this->Bayon->userId());
                    }else{
                        $this->set('company', $company);
                        $this->set('error', true);
                    }
                   
                }
            }

        }
        public function index() {
		
		$this->Company->recursive = 0;
		$this->set('companies', $this->paginate());
		
	}
        public function changeLogo(){
           
            if(!empty($this->data)){
                $path = WWW_ROOT.'files'.DS.'company'.DS.'logo';
                if(!$this->data['Company']['logo']['name']){
                    $this->Session->setFlash(__('Please select your image!', true));
                    $this->redirect('/company/change_logo/'.$this->data['Company']['id']);
                }

		$this->Upload->upload($this->data['Company']['logo']);
                if ($this->Upload->file_is_image){
                    
                    //logo default size 160
                    $this->Upload->image_resize = true;
                    $this->Upload->image_ratio_y = true;
                    $this->Upload->image_x = 160;
                    $this->Upload->file_new_name_body = 'default_'.$this->data['Company']['guid'];
                    $this->Upload->process( $path );
                   $default =  $this->Upload->file_dst_name;
                   $default = FULL_BASE_URL.$this->base.'/files/company/logo/'.$default;

                    //logo 48x48
                    $this->Upload->image_resize      = true;
                    //$this->Upload->image_ratio_y = true;
                    $this->Upload->image_y = 48;
                    $this->Upload->image_x = 48;
                    $this->Upload->file_new_name_body = $this->data['Company']['guid'].'_48';
                    $this->Upload->process( $path );
                    $logo48 =  $this->Upload->file_dst_name;
                    $logo48 = FULL_BASE_URL.$this->base.'/files/company/logo/'.$logo48;

                    //update current logo
                    $this->Company->id = $this->data['Company']['id'];
                    $this->Company->saveField('logo', $default);
                    $this->Company->saveField('logo_48', $logo48);
                    
                    $this->redirect($this->data['Company']['slug']);
                     
                }else{
			$this->Session->setFlash(__('This file type not allow!', true));
                        $this->redirect('/company/change_logo/'.$this->data['Company']['id']);
		}
            }else{
                $companyId = $this->params['companyid'];
                if(!$companyId){
                    $this->Session->setFlash(__('Invalid company id.'));
                }else{
                    $this->set('company', $this->Company->find('first', array('conditions' => array('Company.id' => $companyId), 'recursive' => -1)));
                }
            }
        }

/**
 * View companies by category (classification)
 *
 * @param string $name name of classification
 * @param int $id id of classification
 */

    public function category($name, $id){
           if($id){
               $this->paginate = array('order' => 'Company.name', 'limit' => 2);
               $condition = array('Classification.id' => $id);

               $this->set('data', $this->paginate('ClassificationCompany', $condition));
            }else{
                //invalide classification id
               $this->cakeError('error404');
            }

        }

/**
 * Report company for user to report a company
 *
 */
    public function report(){
        
    }
/**
 * Share to social media
 *
 */
    public function shareCompany($id){
        $this->Company->recursive = -1;
        $this->set('company', $this->Company->read($id));
    }

/**
 * 
 * @param int $companyId
 * @param int $properties
 */
	public function viewCompany() {
            
            $guid = $this->params['guid'];
            if($guid){
                $company = $this->Company->find('first', 
                        array(
                            'conditions' => array('Company.guid' => $guid), 'recursive' => 0,
                            'fields' => array(
                                'Company.name',
                                'Company.slug',
                                'Company.guid',
                                'Company.house_number',
                                'Company.street',
                                'Company.city',
                                'Company.logo',
                                'Company.phone',
                                'Company.country_id',
                                'Company.tel',
                                'Company.email',
                                'Company.fax',
                                'Company.website',
                                'Company.pobox',
                                'Company.description',
                                'Company.user_id',
                                'Country.name',
                                'User.username',
                                'Product' => null,
                                'Service' => null

                            )
                     ));

                //get other company
                $otherCompanies = $this->Company->find('all',
                        array(
                            'conditions' => array('Company.user_id' => $company['Company']['user_id'],'Company.guid != ' => $guid),
                            'fields' =>array(
                                'Company.name',
                                'Company.slug',
                                'Company.logo_48',
                           ),
                           'recursive' => -1
                        )
                  );
                $this->set('otherCompanies', $otherCompanies);
                $this->set('company',  $company);

                //selecte related company
                $clasCompany = $this->Company->ClassificationCompany->find('first', array('conditions' => array('ClassificationCompany.company_id' => $company['Company']['id']), 'recursive' => -1));
                $relatedCompanies = $this->Company->ClassificationCompany->find('all', array('conditions' => array('ClassificationCompany.classification_id' => $clasCompany['ClassificationCompany']['classification_id'], 'ClassificationCompany.company_id != ' => $company['Company']['id'], 'Company.user_id != ' => $company['Company']['user_id']), 'limit' => 6));
                //$relatedCompanies = $this->Company->ClassificationCompany->find('all', array('conditions' => array('ClassificationCompany.classification_id' => $clasCompany['ClassificationCompany']['classification_id']), 'limit' => 6));
               $this->set('relatedCompanies', $relatedCompanies);

               //initial likes
               $this->loadModel('Like');
               $this->set('liked', $this->Like->checkLike($this->Bayon->userId(), $company['Company']['id'], OBJECT_TYPE_COMPANY));
               $likes = $this->Like->getLikes($company['Company']['id'], OBJECT_TYPE_COMPANY);
               $totalLike = $this->Like->totalLikes($company['Company']['id'], OBJECT_TYPE_COMPANY);
               $this->set('totalLike', $totalLike);
               $this->loadModel('Avatar');
               $peopleLike = array();
               $i = 0;
               foreach($likes as $like){
                   $avatar = $this->Avatar->getAvatar($like['User']['id'], AVATAR_WIDHT_48);;
                   $peopleLike[$i]['name'] = $like['User']['name'];
                   $peopleLike[$i]['username']  = $like['User']['username'];
                   $peopleLike[$i]['avatar'] =  $avatar;
                   $i++;

               }
               $this->set('peopleLike', $peopleLike);
            }else{
                 $this->cakeError('error404');
            }
	}
        public function view(){
            pr($this->params); die();
        }

	public function setupCompany(){
            if(!empty($this->data)){

                    $this->data['Company']['guid'] = $this->data['Company']['slug'];
                    $slug = FULL_BASE_URL.$this->base.'/company/'.$this->data['Company']['slug'];
                    $this->data['Company']['slug'] = $slug;
                    $this->data['Company']['user_id'] = $this->Bayon->userId();
                   // pr($this->data); die();

                    $this->Company->create();
                    if($this->Company->save($this->data)){
                        $companyId = $this->Company->id;
                        
                        if(isset($this->data['Company']['children']))
                           $classifyId = $this->data['Company']['children'];
                        else
                           $classifyId = $this->data['Company'] ['classification'];
                        
                        //add classificatinCompany
                        $this->Company->ClassificationCompany->addClassificationCompany($companyId,  $classifyId);

                        $this->loadModel('Classification');
                        $this->Classification->updateAll(
                                    array('Classification.total_item' => 'Classification.total_item + 1'),
                                    array('Classification.id' => $classifyId)
                                );

                        //first add company we need to write session
                        $this->Session->write($this->Bayon->username().'_first_add_company', true);

                        //update notice when add new company complete
                        $notice = array(
                                'Notice' =>array(
                                    'user_id' => $this->Bayon->userId(),
                                    'message' => __('add a company ', true).'<strong>'.$this->data['Company']['name'].'</strong> <a href="'.$slug.'">'.__('view detail', true).'</a>',
                                    'render' =>  __('add a company ', true).'<strong>'.$this->data['Company']['name'].'</strong> <a href="'.$slug.'">'.__('view detail', true).'</a>',
                                    'source' => BAYON_SOURCE_WEB,
                                    'created' => date('Y-m-d h:i:s'),
                                )
                            );

                        //update to notice front page
                        $this->loadModel('Notice');
                        $this->Notice->addNotice($notice);

                        //update user status
                        $this->loadModel('UserStatus');
                       //add notice counter
                        $this->UserStatus->updateUserStatus($this->Bayon->userId(), STATUS_NOTICE, '+');
                        //set company status as percentage
                        $this->UserStatus->updateUserStatus($this->Bayon->userId(), STATUS_COMPANY, null, 60);

                        
                        $this->Session->setFlash(__('Company has been created. Start to add first product', true));
                        $this->redirect(array('controller' => 'products', 'action' =>'addNewProduct'));

                    }
		}else{
			$countries = $this->Company->Country->find('list', array('recursive' => -1));
			$this->set('countries', $countries);
                        $this->set('userId', $this->Bayon->userId());
			$this->loadModel('Classification');
			$this->set('classifications', $this->Classification->getClassifications());
		}
		
	}
	

	
}
?>